import { t } from 'i18next'

import { Search } from '@kedacom/react-next'
import { StyledWrap } from './style'
import { IconInfo } from '../../components/Icons'
import { CONSTANT } from '../../utils/utils'
import PendingList from './list'
import { getItemInPending } from '../../translator'
import { usePendingStore } from './store'
import { useSearch } from './hooks'
import shallow from 'zustand/shallow'
import { itemAddToRight } from '../../store.trans'

function Pending() {
	const { value, onSearch, searchAll } = useSearch()
	const { isSearch, searchType, totalNum, collapsedAll } = usePendingStore(
		(state) => ({
			isSearch: state.isSearch,
			searchType: state.searchType,
			totalNum: state.totalNum,
			collapsedAll: state.collapsedAll,
		}),
		shallow
	)
	const handleEnter = () => {
		if (totalNum === 1) {
			const tree = usePendingStore.getState().tree
			getItemInPending(tree, (item) => {
				if (item.users.length > 0) {
					itemAddToRight(item.users[0], 'auto')
					return false
				}
			})
		}
	}
	return (
		<StyledWrap>
			<div className="search-wrap">
				<Search
					iconAlign="left"
					value={value}
					placeholder={t('请输入关键字搜索')}
					onChange={(e, v) => onSearch(v)}
					onClear={() => onSearch('')}
					onEnter={handleEnter}
					clearable
					maxLength={128}
				/>
			</div>
			<div className="search-result-tips">
				{isSearch && <span className="search-num">{t('搜索结果({{totalNum}})', { totalNum: totalNum })}</span>}
				<span className="decoration-underline" onClick={collapsedAll}>
					{t('全部收起')}
				</span>
			</div>
			<div className="pending-content">
				<PendingList />
				{totalNum === 0 && isSearch && (
					<div className="empty">
						<IconInfo />
						<span>{t('没有匹配的搜索结果')}</span>
					</div>
				)}
			</div>
			{/* 简单搜索 >5个 显示tip */}
			{isSearch && searchType === CONSTANT.searchType.simple && totalNum > 5 && (
				<div className="more-content">
					<span className="decoration-underline" onClick={searchAll}>
						{t('更多({{totalNum}})条结果', { totalNum: totalNum })}
					</span>
				</div>
			)}
		</StyledWrap>
	)
}
export default Pending
